package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Rulecolumn;
import cn.edu.scau.cmi.ema.domain.Rulefield;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("RulecolumnService")
@Transactional

public class RulecolumnServiceImpl extends CmiEmaService implements RulecolumnService {
	public RulecolumnServiceImpl() {
	}

	@Transactional
	public Rulecolumn saveRulecolumn(Rulecolumn rulecolumn) {

		if (rulecolumn.getId() == null) {
			Rulefield rulefield = rulefieldDAO.findRulefieldById(rulecolumn.getRulefield().getId());

			Rulecolumn existingRulecolumn = rulecolumnDAO.findRulecolumnByPhysicalPrimaryKey(rulefield.getId(),
					rulecolumn.getExcelcolumn(), rulecolumn.getPartion());

			rulecolumn.setRulefield(rulefield);

			if (isEquals(rulecolumn, existingRulecolumn)) {
				return existingRulecolumn;
			}

			rulecolumn = rulecolumnDAO.store(rulecolumn);
			rulecolumnDAO.flush();

		} else {
			Rulecolumn existingRulecolumn = rulecolumnDAO.findRulecolumnByPrimaryKey(rulecolumn.getId());

			rulecolumn = rulecolumnDAO.store(rulecolumn);
			rulecolumnDAO.flush();
		}

		return rulecolumn;
	}

	public void deleteRulecolumn(Rulecolumn rulecolumn) {
		rulecolumnDAO.remove(rulecolumn);
		rulecolumnDAO.flush();
	}

	@Transactional
	public void deleteRulecolumns(Set<Integer> deleteRulecolumnsId) {
		Query query = rulecolumnDAO.createNamedQuery("deleteRulecolumnsById", -1, -1);
		query.setParameter(1, deleteRulecolumnsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Rulecolumn> loadRulecolumns() {
		return rulecolumnDAO.findAllRulecolumns();

	}

	@Transactional
	public Set<Rulecolumn> loadReferenceRulecolumns(Set<Rulecolumn> rulecolumns) {
		Iterator<Rulecolumn> rulecolumnsIterator = rulecolumns.iterator();
		Set<Rulecolumn> referencedRulecolumns = new HashSet<>();
		while (rulecolumnsIterator.hasNext()) {
			Rulecolumn currentRulecolumn = rulecolumnsIterator.next();

		}
		return referencedRulecolumns;
	}

	public Set<Rulecolumn> loadRulecolumnsByIdSet(Set<Integer> rulecolumnIdSet) {

		Iterator<Integer> rulecolumnIdIterator = rulecolumnIdSet.iterator();
		Set<Rulecolumn> rulecolumnSet = new HashSet<>();
		while (rulecolumnIdIterator.hasNext()) {
			Integer id = rulecolumnIdIterator.next();
			Rulecolumn currentRulecolumn = rulecolumnDAO.findRulecolumnById(id);
			rulecolumnSet.add(currentRulecolumn);
		}
		return rulecolumnSet;
	}

	@Transactional
	public List<Rulecolumn> findAllRulecolumns(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Rulecolumn>(rulecolumnDAO.findAllRulecolumns(startResult, maxRows));
	}

	@Transactional
	public Rulecolumn findRulecolumnByPrimaryKey(Integer id) {
		return rulecolumnDAO.findRulecolumnByPrimaryKey(id);
	}

	@Transactional
	public Integer countRulecolumns() {
		return ((Long) rulecolumnDAO.createQuerySingleResult("select count(o) from Rulecolumn o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countRulecolumns(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Rulecolumn.class);
		return ((Long) rulecolumnDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countRulecolumnsByName(String queryName) {
		Query query = rulecolumnDAO.createNamedQuery("countRulecolumnsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countRulecolumnsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Rulecolumn.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadRulecolumnObjectReferencedSet(Rulecolumn rulecolumn) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (rulecolumn.getRulefield() != null) {

			Set<Integer> rulefieldIds = new HashSet<Integer>();
			rulefieldIds.add(rulecolumn.getRulefield().getId());
			objectReferencedSetMap.put("rulefieldIds", rulefieldIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadRulecolumnClassReferencedSet(Rulecolumn rulecolumn) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("rulefields", rulefieldDAO.findAllRulefields());

		return classReferencedSetMap;
	}

	public boolean isEquals(Rulecolumn rulecolumn, Object obj) {
		if (obj == rulecolumn)
			return true;
		if (!(obj instanceof Rulecolumn))
			return false;
		Rulecolumn comparedRulecolumn = (Rulecolumn) obj;
		if (!CheckPropertyEqual(rulecolumn.getRulefield().getId(), comparedRulecolumn.getRulefield().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(rulecolumn.getExcelcolumn(), comparedRulecolumn.getExcelcolumn())) {
			return false;
		}
		if (!CheckPropertyEqual(rulecolumn.getPartion(), comparedRulecolumn.getPartion())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

